//
//  CustomDetailViewController.m
//  NewsReader
//
//  Created by blacksun on 10-11-10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "CustomDetailViewController.h"
#import "FeedDetailViewController.h"
#import "ItemListController.h"


@implementation CustomDetailViewController

@synthesize currentIndex,feeds,scrollView,operationQueue,loadingView,parentController;
@synthesize freeDetailControllers;
@synthesize workingControllers;

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	NSOperationQueue *queue = [[NSOperationQueue alloc] init];
	[queue setMaxConcurrentOperationCount:5];
	self.operationQueue = queue;
	[queue release];
	
	//给图片加圆角
	self.loadingView.layer.cornerRadius = 6;
	self.loadingView.layer.masksToBounds = YES;
	lastIndex = self.currentIndex;
	
	[self.parentController addNotificationAbserver:self selector:@selector(updateSucess)];
	self.scrollView.delegate = self;
	self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * [self.feeds count], self.scrollView.frame.size.height);
	self.freeDetailControllers = [NSMutableArray array];
	self.workingControllers = [NSMutableDictionary dictionary];
	
	for (int i=0; i<5; i++) {
		FeedDetailViewController *child =  [[FeedDetailViewController alloc] initWithNibName:@"FeedDetailViewController" bundle:nil];
		[self.freeDetailControllers addObject:child];
		[child release];
	}
	[self loadScrollViewWithPage:self.currentIndex];
	CGRect frame = self.scrollView.frame;
	frame.origin.x = frame.size.width * currentIndex;
    frame.origin.y = 0;
    [self.scrollView scrollRectToVisible:frame animated:NO];
	NSString *indexStr = [[NSString alloc] initWithFormat:@"%d",self.currentIndex];
	[self performSelector:@selector(displayView:) withObject:indexStr afterDelay:0.2];
	[indexStr release];
}

-(void)updateSucess{
	isUpdateing = NO;
	self.loadingView.hidden = YES;
	self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * [self.feeds count], self.scrollView.frame.size.height);
	if (self.currentIndex+1 < [self.feeds count]) {
		self.currentIndex = currentIndex+1;
		[self loadScrollViewWithPage:self.currentIndex];
		CGRect frame = self.scrollView.frame;
		frame.origin.x = frame.size.width * self.currentIndex;
		frame.origin.y = 0;
		[self.scrollView scrollRectToVisible:frame animated:YES];
		lastRestIndex = self.currentIndex;
		[self performSelector:@selector(scrollViewDidEndDecelerating:) withObject:self.scrollView afterDelay:0.3];
	}
}

- (void)setUpDetailController:(NSInteger )index{
	CGRect frame = scrollView.frame;
	NSString *indexStr = [[NSString alloc] initWithFormat:@"%d",index];
	FeedDetailViewController *currentController =  [self.workingControllers objectForKey:indexStr];
	if (currentController == nil) {
		currentController  = [self.freeDetailControllers lastObject];
		currentController.view.frame = CGRectMake(frame.size.width * index, 0.0, 320.0, 460.0);
		if (currentController.view.superview == nil) {
			[self.scrollView addSubview:currentController.view];
		}
		[currentController reset:[self.feeds objectAtIndex:index]];
		[self.workingControllers setObject:currentController forKey:indexStr];
		[self.freeDetailControllers removeLastObject];
	}

	[indexStr release];
}

- (void)removeDetailController:(NSInteger)index{
	NSString *indexStr = [[NSString alloc] initWithFormat:@"%d",index];
	FeedDetailViewController *currentController =  [self.workingControllers objectForKey:indexStr];
	if (currentController != nil) {
		[currentController.view removeFromSuperview];
		[currentController reset:nil];
		[self.freeDetailControllers addObject:currentController];
		[self.workingControllers removeObjectForKey:indexStr];
	}
	[indexStr release];
}

- (void)loadScrollViewWithPage:(NSInteger)page {
	if (page<0 || page>=[self.feeds count]) return;
	//当前
	[self setUpDetailController:page];
	
	//上一个
	if (page-1>=0) {
		[self setUpDetailController:page-1];
	}
	//下一个
	if (page+1<[self.feeds count]) {
		[self setUpDetailController:page+1];	
	}
	//删除前后两个多余的
	if (page-2>=0) {
		[self removeDetailController:page-2];
	}
	if (page+2<[self.feeds count]) {
		[self removeDetailController:page+2];
	}
}

-(void)displayView:(NSString *) indexStr{
	FeedDetailViewController *controller = [self.workingControllers objectForKey:indexStr];
	[controller displayDetail];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	lastIndex = self.currentIndex;
	lastRestIndex = self.currentIndex;
}

-(void) viewWillDisappear:(BOOL)animated{
	[super viewWillDisappear:animated];
	NSArray *feedDetailControllers = [self.workingControllers allValues];
	[feedDetailControllers makeObjectsPerformSelector:@selector(stopAllImageDownloading)];
}

- (void)scrollViewDidScroll:(UIScrollView *)aScrollView{	
	CGFloat pageWidth = aScrollView.frame.size.width;
    int page = floor((aScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
	[self loadScrollViewWithPage:page];	
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)aScrollView{
	CGFloat pageWidth = aScrollView.frame.size.width;
    int page = floor((aScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
	self.currentIndex = page;
	//清除上左右两个feed的detail
	if (page-1>=0) {
		NSString *indexStr = [[NSString alloc] initWithFormat:@"%d",page-1];
		FeedDetailViewController *lastController =  [self.workingControllers objectForKey:indexStr];
		[lastController removeDetail];
		[indexStr release];
	}
	if (page+1<[self.feeds count]) {
		NSString *indexStr = [[NSString alloc] initWithFormat:@"%d",page+1];
		FeedDetailViewController *nextController =  [self.workingControllers objectForKey:indexStr];
		[nextController removeDetail];
		[indexStr release];
	}//清除结束
	
	
	NSString *indexStr = [[NSString alloc] initWithFormat:@"%d",page];
	[self displayView:indexStr];
	[indexStr release];
	if (self.currentIndex==lastIndex && self.currentIndex==([self.feeds count]-1) && !isUpdateing ) {
		isUpdateing = YES;
		[self.parentController loadOlderFeeds];
		[self showLoadingView:YES];
	}
	
	if (isUpdateing && (self.currentIndex == [self.feeds count]-1)) {
		[self showLoadingView:YES];
	}
	else {
		[self showLoadingView:NO];
	}
		
	lastIndex = currentIndex;
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	[self.parentController.newItems makeObjectsPerformSelector:@selector(setIcon:) withObject:nil];
	Feed *lastFeed = nil;
	Feed *currentFeed = nil;
	Feed *nextFeed = nil;
	
	NSArray *lastContents = nil;
	NSArray *currentContents = nil;
	NSArray *nextContents = nil;
	if (self.currentIndex-1>=0) {
		lastFeed = [self.parentController.newItems objectAtIndex:(self.currentIndex-1)];
		lastContents = [lastFeed.details retain];
	}		
	currentFeed = [self.parentController.newItems objectAtIndex:(self.currentIndex)];
	currentContents = [currentFeed.details retain];
	
	if (self.currentIndex+1<[parentController.newItems count]) {
		nextFeed = [self.parentController.newItems objectAtIndex:(self.currentIndex+1)];
		nextContents = [nextFeed.details retain];
	}
	[self.parentController.newItems makeObjectsPerformSelector:@selector(setDetails:) withObject:nil];
	if (lastContents) {
		lastFeed.details = lastContents;
	}
	currentFeed.details = currentContents;
	if (nextContents) {
		nextFeed.details = nextContents;
	}
	[lastContents release];
	[currentContents release];
	[nextContents release];
}


/*
- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}*/

- (void)showLoadingView:(BOOL)needAnimation{
	self.loadingView.alpha = 1.0;
	UILabel *label = (UILabel *)[self.loadingView viewWithTag:100];
	UIActivityIndicatorView *activity = (UIActivityIndicatorView *)[self.loadingView viewWithTag:101];
	label.frame = CGRectMake(10.0, 0.0, 40.0, 20.0);
	activity.hidden = YES;
	
	NSString *labelText = [[NSString alloc] initWithFormat:@"%d/%d",self.currentIndex+1,[self.feeds count]];
	label.text = labelText;
	[labelText release];
	
	if (needAnimation) {
		label.frame = CGRectMake(0.0, 0.0, 40.0, 20.0);
		activity.hidden = NO;
		
	}else {
		[UIView beginAnimations:nil context:nil];
		[UIView setAnimationDuration:2.0];
		self.loadingView.alpha = 0.0;
		[UIView commitAnimations];
	}

	self.loadingView.hidden = NO;
	
}

- (void)dealloc {
	[self.freeDetailControllers release];
	[self.workingControllers release];
	[self.operationQueue cancelAllOperations];
	[self.operationQueue release];
	[self.loadingView release];
	[self.feeds release];
	[self.scrollView release];
	[self.parentController removeNotificationAbserver:self];
	self.parentController = nil;
    [super dealloc];
}


@end

